#include "SeqStack.hpp"
#include <cstdlib>
#include <iostream>
#include <stack/SeqStack.hpp>

Status initStack(SeqStackPtr ptr)
{
    ElemType *elem=(ElemType*)(malloc(STACK_INIT_SIZE * sizeof(ElemType)));
    if (!elem ) return OVERFLOW;
    ptr->base=ptr->top=elem;
    ptr->statckSize= STACK_INIT_SIZE;
    return OK;
}

Status clearStack(SeqStackPtr ptr)
{
    ptr->top=ptr->base;
    return OK;
}

Status destoryStack(SeqStackPtr ptr)
{
    free(ptr->base);
    ptr->base=ptr->top=NULL;
    ptr->statckSize=0;
    return OK;
}

Status stackEmpty(SeqStackPtr ptr)
{
    if(ptr->top==ptr->base) return TRUE;
    return FALSE;
}

long stackLength(SeqStackPtr ptr)
{
    return ptr->top - ptr->base;
}

Status  getTop(SeqStackPtr ptr,ElemType &e)
{
    if (!stackEmpty(ptr))
    {
        e=*(ptr->top-1);
        return OK;
    }
    else
    {
        return ERROR;
    }
}

Status push(SeqStackPtr ptr,ElemType e)
{
    if (stackLength(ptr)==ptr->statckSize)
    {
        ptr->base=(ElemType *)realloc(ptr->base,(ptr->statckSize+ STACKNCREMENT)* sizeof(ElemType));
        if ( !ptr->base ) exit(OVERFLOW);
        ptr->statckSize=ptr->statckSize+ STACKNCREMENT;

    }
        * ptr->top++ = e;
        return OK;
}

Status  pop(SeqStackPtr ptr,ElemType &e)
{
    if (stackEmpty(ptr)) return ERROR;

    e=* --ptr->top;
    return OK;
}

Status  stackTraverse(SeqStackPtr ptr,Status (*visit)(ElemType))
{
    while(ptr->top> ptr->base)
        visit(* --ptr->top);
    printf("\n");
    return OK;
}